'use strict'

module.exports = angular.module 'libs.utils.ztree', []
.factory 'ZTreeService',($log)->
  $log.log "custom-ztree service init"
  class ZTreeService
    constructor: (options)->
      @newCount = 1 # test
      defaultOptions =
        "treeId": "tree"
      @treeOptions = {}
      angular.extend @treeOptions, defaultOptions, options

    getZTreeObject: ->
      $.fn.zTree.getZTreeObj(@treeOptions.treeId)

    # addCb: 新增节点
    # uploadCb: 上传节点icon
    # activeCb: 节点可见
    # activeCb: 节点不可见
    addHoverDom: (treeId, treeNode, addCb, activeCb, inactiveCb)->
      if !treeNode.editNameFlag && $("#addBtn_" + treeNode.tId).length <= 0 && !treeNode.parentId
        addHtml = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='add node' onfocus='this.blur()'></span>"
        $("#" + treeNode.tId + "_span").after addHtml
        $addBtn = $("#addBtn_" + treeNode.tId)
        if $addBtn
          $addBtn.bind "click", ->
            addCb() if addCb
            return false
      if $("#activeBtn_" + treeNode.tId).length <= 0 && $("#inactiveBtn_" + treeNode.tId).length <= 0
        if !treeNode.active
          activeHtml = "<span class='button active' id='activeBtn_" + treeNode.tId + "' title='active node' onfocus='this.blur()'></span>"
          $("#" + treeNode.tId + "_remove").after activeHtml
          $activeBtn = $("#activeBtn_" + treeNode.tId)
          if $activeBtn
            $activeBtn.bind "click", ->
              activeCb() if activeCb
              return false
          return

        inactiveHtml = "<span class='button inactive' id='inactiveBtn_" + treeNode.tId + "' title='inactive node' onfocus='this.blur()'></span>"
        $("#" + treeNode.tId + "_remove").after inactiveHtml
        $inactiveBtn = $("#inactiveBtn_" + treeNode.tId)
        if $inactiveBtn
          $inactiveBtn.bind "click", ->
            inactiveCb() if inactiveCb
            return false

    removeHoverDom: (treeId, treeNode)->
      $("#addBtn_" + treeNode.tId).unbind().remove()
      $("#activeBtn_" + treeNode.tId).unbind().remove()
      $("#inactiveBtn_" + treeNode.tId).unbind().remove()

    dropInner: (treeId, nodes, targetNode)->
      return false if targetNode and !targetNode.dropInner
      return false if nodes[0].children and nodes[0].children.length > 0
      nodes[0].dropInner = false
      return true

    dropPrev: (treeId, nodes, targetNode)->
      return true if ( nodes[0].parentId == null and targetNode.parentId == null ) || nodes[0].parentId is targetNode.parentId
      return false

    dropNext: (treeId, nodes, targetNode)->
      return true if ( nodes[0].parentId == null and targetNode.parentId == null ) || nodes[0].parentId is targetNode.parentId
      return false
